package org.example.utils;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

@Slf4j
public class XmlBuilder {

    /**
     * 将XML转为指定的POJO对象
     *
     * @param clazz  需要转换的类
     * @param xmlStr xml数据
     * @return
     */
    public static Object xmlStrToObject(Class<?> clazz, String xmlStr) {
        try {
            Object xmlObject = null;
            Reader reader = null;
            //利用JAXBContext将类转为一个实例
            JAXBContext context = JAXBContext.newInstance(clazz);
            //XMl 转为对象的接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(reader);
            if (reader != null) {
                reader.close();
            }
            return xmlObject;
        } catch (Exception e) {
            log.error("xml解析错误", e);
            return null;
        }
    }

    public static String objectToXmlStr(Object object) {
        StringWriter sw = null;
        try {
            //利用JAXBContext将类转为一个实例
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            //XMl 转为对象的接口
            Marshaller marshaller = context.createMarshaller();
            sw = new StringWriter();
            marshaller.marshal(object,sw);
            return sw.toString();
        } catch (Exception e) {
            log.error("xml解析错误", e);
        }finally {
            if (sw != null) {
                try {
                    sw.close();
                }catch (Exception e){
                    log.error("close错误", e);
                }
            }
        }
        return null;
    }
}
